import {
  Catch,
  ExceptionFilter,
  HttpException,
  ArgumentsHost,
  Logger
} from '@nestjs/common';
import { ApiException } from '../exceptions/api.exception';
import * as httpProxy from 'http-proxy';
import config from '@/config/config';

// 创建代理对象
const proxy = httpProxy.createProxyServer({
  // 代理地址为http时
  target: config.target,
  // 是否需要改变原始主机头为目标URL
  changeOrigin: true
});
// 配置错误处理
proxy.on('error', (err, request, response) => {
  response.writeHead(500, {
    'Content-Type': 'text/plain'
  });
  response.status(500).end('服务器异常！');
});

@Catch()
export class HttpErrorFilter implements ExceptionFilter {
  catch(exception, host: ArgumentsHost) {
    // 接受promise错误并打印出exception内容
    process.on('unhandledRejection', (reason: any, promise: Promise<any>) => {
      // console.error('UnhandledPromiseRejectionWarning>>>', exception);
    });

    const ctx = host.switchToHttp();
    const request = ctx.getRequest();
    const response = ctx.getResponse();
    const status = exception.getStatus();
    let errorResponse;

    if (status === 404) {
      // 找不到的接口都做代理转发
      proxy.web(request, response);
      return;
    }

    if (exception instanceof ApiException) {
      // 自定义的错误码
      errorResponse = {
        errorCode: exception.getErrorCode(),
        errorMessage: exception.getErrorMessage(),
        timestamp: new Date().toLocaleDateString(),
        path: request.path,
        method: request.method
      };
    } else {
      // 非自定义的错误码
      errorResponse = {
        code: status,
        timestamp: new Date().toLocaleDateString(),
        path: request.path,
        method: request.method,
        message: exception.message.error || exception.message || null
      };
    }

    Logger.error(
      `${request.method} ${request.url}`,
      JSON.stringify(errorResponse),
      'ExceptionFilter'
    );

    response.status(status).json(errorResponse);
  }
}
